/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iketest;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Pouja
 */
public class User {
    private List<Song> songs;
    private String name;
    public User(String name){
        songs=new ArrayList<Song>();
        this.name=name;
    }
    
    public void addSong(Song song){
        songs.add(song);
    }
    
    static final Comparator<Song> ASCENDING =
    new Comparator<Song>() {
    public int compare(Song e1, Song e2) {
        if(e2.date().before(e1.date())){
            return 1;
        }
        return -1;
    }
    };
    
    public void sort(){
        Collections.sort(songs,ASCENDING);
    }
    
    public void createFile(){
        this.sort();
        try {
            FileWriter simulate=new FileWriter("simulate//"+name+".json");
            BufferedWriter outS=new BufferedWriter(simulate);
            FileWriter test=new FileWriter("test//"+name+"TEST.json");
            BufferedWriter outT=new BufferedWriter(test);
            
            int max=(int)0.2*songs.size();
            int count=0;
            
            outS.write("{\"songs\":");
            outT.write("{\"songs\":");
            
            for(int i=0;i<songs.size();i++){
                if(count>max){
                    outS.write(songs.get(i).toJSON()+",");
                }
                else{
                    if(Math.random()<=0.2&&i+1<songs.size()){
                        outT.write(songs.get(i).toJSON()+",");
                        i++;
                        outT.write(songs.get(i).toJSON()+",");
                    }
                    else{
                        outS.write(songs.get(i).toJSON()+",");
                    }
                }
            }
            outS.write("{}}");
            outT.write("{}}");
            outS.close();
            outT.close();
        } catch (IOException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    
    public String toJSON(){
        String out="{name:"+name+",";
        for(int i=0;i<songs.size();i++){
            if(i==songs.size()-1){
                out+="["+songs.get(i).toJSON()+"]";
            }
            else{
                out+="["+songs.get(i).toJSON()+"],";
            }
        }
        out+="}";
        return out;
    }
    
    public String name(){
        return this.name;
    }
}
